﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Utils
{
    public class ImageExtension
    {
        public static System.Drawing.Image FromByteToImage(byte[] value)
        {
            if (value != null)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    stream.Write(value, 0, value.Length);
                    return System.Drawing.Image.FromStream(stream, true);
                }
            }
            else { return null; }
        }

        public static byte[] FromImageToByte(System.Drawing.Image image)
        {
            if (image != null)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                    return stream.ToArray();
                }
            }
            else { return null; }
        }

        public static byte[] FromStreamToByte(Stream content)
        {
            byte[] buffer = new byte[16384];
            MemoryStream ms = new MemoryStream();
            int bytesRead, totalBytesRead = 0;
            do
            {
                bytesRead = content.Read(buffer, 0, buffer.Length);
                totalBytesRead += bytesRead;

                ms.Write(buffer, 0, bytesRead);
            } while (bytesRead > 0);

            return ms.ToArray();
        }
    }
}
